@page "/exams"
@inject IExamService ExamService
@inject ILocalStorageService LocalStorage
@inject ILogService LogService
@inject NavigationManager Navigation

<PageTitle>试卷管理</PageTitle>

<div>
    <Title Level="2">试卷管理</Title>
    
    <div style="margin: 16px 0;">
        <Row Gutter="16">
            <Col Span="6">
                <Select @bind-Value="selectedChildId" 
                        Placeholder="选择孩子" 
                        Style="width: 100%;"
                        OnChange="FilterByChild"
                        TItemValue="int"
                        TItem="int">
                    <SelectOption Value="0" Label="全部孩子" TItemValue="int" TItem="int" />
                    @if (children?.Any() == true)
                    {
                        @foreach (var child in children)
                        {
                            <SelectOption Value="child.Id" Label="child.Name" TItemValue="int" TItem="int" />
                        }
                    }
                </Select>
            </Col>
            <Col Span="6">
                <Select @bind-Value="selectedExamType" 
                        Placeholder="试卷类型" 
                        Style="width: 100%;"
                        OnChange="FilterByType"
                        TItemValue="string"
                        TItem="string">
                    <SelectOption Value="@string.Empty" Label="全部类型" TItemValue="string" TItem="string" />
                    @foreach (var type in ExamTypes.GetAll())
                    {
                        <SelectOption Value="type" Label="type" TItemValue="string" TItem="string" />
                    }
                </Select>
            </Col>
            <Col Span="6">
                <Button Icon="reload" OnClick="RefreshData">
                    刷新
                </Button>
                <Button Type="@ButtonType.Primary" 
                        Icon="file-add" 
                        OnClick="NavigateToGenerate"
                        Style="margin-left: 8px;">
                    生成试卷
                </Button>
            </Col>
        </Row>
    </div>
    
    @if (loading)
    {
        <Spin Spinning="true" Size="large">
            <div style="height: 300px;"></div>
        </Spin>
    }
    else if (displayExams?.Any() == true)
    {
        <Row Gutter="16">
            @foreach (var exam in displayExams)
            {
                <AntDesign.Col Span="8" Style="margin-bottom: 16px;">
                    <Card Hoverable 
                          Actions="GetCardActions(exam)">
                        <CardMeta Title="@exam.Title" 
                                  Description="@GetExamDescription(exam)" />
                        <div style="margin-top: 12px;">
                            <Space Direction="DirectionVHType.Vertical" Size="@("4")">
                                <SpaceItem>
                                    <Text Type="secondary">
                                        <Icon Type="user" /> @GetChildName(exam.ChildId)
                                    </Text>
                                </SpaceItem>
                                <SpaceItem>
                                    <Text Type="secondary">
                                        <Icon Type="file-text" /> @exam.Type
                                    </Text>
                                </SpaceItem>
                                <SpaceItem>
                                    <Text Type="secondary">
                                        <Icon Type="clock-circle" /> @exam.CreateTime.ToString("yyyy-MM-dd HH:mm")
                                    </Text>
                                </SpaceItem>
                                <SpaceItem>
                                    <Space Size="@("8")">
                                        <SpaceItem>
                                            <Tag Color="blue">@exam.Questions.Count 道题</Tag>
                                        </SpaceItem>
                                        <SpaceItem>
                                            <Tag Color="green">@exam.Difficulty</Tag>
                                        </SpaceItem>
                                    </Space>
                                </SpaceItem>
                            </Space>
                        </div>
                    </Card>
                </AntDesign.Col>
            }
        </Row>
        
        @if (allExams.Count > displayExams.Count)
        {
            <div style="text-align: center; margin-top: 16px;">
                <Text Type="secondary">
                    显示 @displayExams.Count / @allExams.Count 份试卷
                </Text>
            </div>
        }
    }
    else
    {
        <Empty Description="@("暂无试卷")">
            <Button Type="@ButtonType.Primary" Icon="file-add" OnClick="NavigateToGenerate">
                生成第一份试卷
            </Button>
        </Empty>
    }
</div>

@code {
    private List<ExamPaper> allExams = new();
    private List<ExamPaper> displayExams = new();
    private List<ChildProfile>? children;
    private bool loading = true;
    private int selectedChildId = 0;
    private string selectedExamType = "";
    
    protected override async Task OnInitializedAsync()
    {
        // 从查询参数获取childId
        var uri = new Uri(Navigation.Uri);
        var query = System.Web.HttpUtility.ParseQueryString(uri.Query);
        if (int.TryParse(query["childId"], out int childId))
        {
            selectedChildId = childId;
        }
        
        await LoadData();
    }
    
    private async Task LoadData()
    {
        try
        {
            loading = true;
            
            // 加载孩子列表
            children = await LocalStorage.GetChildrenAsync();
            
            // 加载试卷列表
            allExams = await ExamService.GetExamsAsync();
            
            FilterExams();
            
            await LogService.LogInfoAsync("加载试卷列表", "ExamList");
        }
        catch (Exception ex)
        {
            await LogService.LogErrorAsync($"加载试卷列表失败: {ex.Message}", "ExamList");
        }
        finally
        {
            loading = false;
            StateHasChanged();
        }
    }
    
    private void FilterExams()
    {
        displayExams = allExams.Where(exam =>
        {
            // 按孩子筛选
            if (selectedChildId > 0 && exam.ChildId != selectedChildId)
                return false;
            
            // 按类型筛选
            if (!string.IsNullOrEmpty(selectedExamType) && exam.Type != selectedExamType)
                return false;
            
            return true;
        }).OrderByDescending(e => e.CreateTime).ToList();
    }
    
    private void FilterByChild()
    {
        FilterExams();
        StateHasChanged();
    }
    
    private void FilterByType()
    {
        FilterExams();
        StateHasChanged();
    }
    
    private async Task RefreshData()
    {
        await LoadData();
    }
    
    private void NavigateToGenerate()
    {
        Navigation.NavigateTo("/exams/generate");
    }
    
    private string GetChildName(int childId)
    {
        return children?.FirstOrDefault(c => c.Id == childId)?.Name ?? "未知";
    }
    
    private string GetExamDescription(ExamPaper exam)
    {
        return $"{exam.Difficulty}难度 • {exam.GenerateMode}";
    }
    
    private RenderFragment[] GetCardActions(ExamPaper exam)
    {
        return new RenderFragment[]
        {
            BuildViewButton(exam),
            BuildAnswerButton(exam),
            BuildMoreActionsDropdown(exam)
        };
    }
    
    private RenderFragment BuildViewButton(ExamPaper exam) => 
        @<Button Type="@ButtonType.Link" Icon="eye" OnClick="() => ViewExam(exam)">查看</Button>;
    
    private RenderFragment BuildAnswerButton(ExamPaper exam) =>
        @<Button Type="@ButtonType.Link" Icon="edit" OnClick="() => DoExam(exam)">答题</Button>;
    
    private RenderFragment BuildMoreActionsDropdown(ExamPaper exam) =>
        @<Dropdown>
            <Overlay>
                <Menu>
                    <MenuItem OnClick="() => PrintExam(exam)">
                        <Icon Type="printer" /> 打印
                    </MenuItem>
                    <MenuItem OnClick="() => ShareExam(exam)">
                        <Icon Type="share-alt" /> 分享
                    </MenuItem>
                    <MenuDivider />
                    <MenuItem OnClick="() => DeleteExam(exam)" Style="color: #ff4d4f;">
                        <Icon Type="delete" /> 删除
                    </MenuItem>
                </Menu>
            </Overlay>
            <ChildContent>
                <Button Type="@ButtonType.Link" Icon="more">更多</Button>
            </ChildContent>
        </Dropdown>;
    
    private void ViewExam(ExamPaper exam)
    {
        Navigation.NavigateTo($"/exams/{exam.Id}");
    }
    
    private void DoExam(ExamPaper exam)
    {
        Navigation.NavigateTo($"/exams/{exam.Id}/answer");
    }
    
    private async Task PrintExam(ExamPaper exam)
    {
        // TODO: 实现打印功能
        await LogService.LogInfoAsync($"打印试卷: {exam.Title}", "ExamList");
    }
    
    private async Task ShareExam(ExamPaper exam)
    {
        // TODO: 实现分享功能
        await LogService.LogInfoAsync($"分享试卷: {exam.Title}", "ExamList");
    }
    
    private async Task DeleteExam(ExamPaper exam)
    {
        try
        {
            var success = await ExamService.DeleteExamAsync(exam.Id);
            if (success)
            {
                await LogService.LogInfoAsync($"删除试卷: {exam.Title}", "ExamList");
                await LoadData();
            }
        }
        catch (Exception ex)
        {
            await LogService.LogErrorAsync($"删除试卷失败: {ex.Message}", "ExamList");
        }
    }
} 